package com.slfx.openapi.client.config;

import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

/**
 * @author slfx
 * @Description:
 * @date 2022/9/18 15:24
 */
@Slf4j
public class RetryIntercepter implements Interceptor {
    /**
     * //最大重试次数
     */
    private int maxRetry;
    /**
     * //假如设置为3次重试的话，则最大可能请求4次（默认1次+3次重试）
     */
    private int retryNum = 0;

    public RetryIntercepter(int maxRetry) {
        this.maxRetry = maxRetry;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        //log.info("重试次数：retryNum="+retryNum);
        Response response = chain.proceed(request);
        while (!response.isSuccessful() && retryNum < maxRetry) {
            retryNum++;
            log.info("Okhttp重试次数：retryNum=" + retryNum);
            response = chain.proceed(request);
        }
        return response;
    }
}
